//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only


import { listen, type UnlistenFn } from '@tauri-apps/api/event';
import type { AllNotice, client as client_notice, board as board_notice } from '$lib/api/notice_type';
import { userStore } from './user.svelte';
import { goto } from '$app/navigation';
import { boardStore } from './board.svelte';

export async function initNoticeStore(): Promise<UnlistenFn> {
    return await listen<AllNotice>("notice", ev => {
        const payload = ev.payload;
        if (payload.ClientNotice != undefined) {
            processClientNotice(payload.ClientNotice);
        } else if (payload.BoardNotice != undefined) {
            processBoardNotice(payload.BoardNotice);
        }
    });
}

async function processClientNotice(notice: client_notice.AllNotice) {
    if (notice.AdminLoginNotice != undefined) {
        userStore.showAdminLoginModal = true;
    }
    if (notice.WrongSessionNotice != undefined) {
        userStore.userSession = "";
        userStore.userInfo = null;
        userStore.adminUserName = "";
        userStore.adminUserSession = "";
        goto("/");
    }
}

async function processBoardNotice(notice: board_notice.AllNotice) {
    if (notice.CreateBoardNotice != undefined) {
        boardStore.onJoinBoard(notice.CreateBoardNotice.board_id);
    } else if (notice.UpdateBoardNotice != undefined) {
        boardStore.onUpdateBoard(notice.UpdateBoardNotice.board_id);
    } else if (notice.RemoveBoardNotice != undefined) {
        boardStore.onRemoveBoard(notice.RemoveBoardNotice.board_id);
    } else if (notice.JoinBoardNotice != undefined) {
        if (notice.JoinBoardNotice.member_user_id == userStore.userInfo?.user_id) {
            boardStore.onJoinBoard(notice.JoinBoardNotice.board_id);
        }
    } else if (notice.LeaveBoardNotice != undefined) {
        if (notice.LeaveBoardNotice.member_user_id == userStore.userInfo?.user_id) {
            boardStore.onRemoveBoard(notice.LeaveBoardNotice.board_id);
        }
    } else if (notice.UpdateBoardMemberPermNotice != undefined) {
        if (notice.UpdateBoardMemberPermNotice.member_user_id == userStore.userInfo?.user_id) {
            boardStore.onUpdateMyPerm(notice.UpdateBoardMemberPermNotice.board_id);
        }
    } else if (notice.CreateDrawNotice != undefined) {
        boardStore.onUpdateBoard(notice.CreateDrawNotice.board_id);
    } else if(notice.NewChatMsgNotice != undefined && notice.NewChatMsgNotice.draw_id == ""){
        boardStore.onUpdateUnreadCount(notice.NewChatMsgNotice.board_id);
    }
}